package client;

import org.apache.log4j.Logger;
import org.springframework.jms.core.JmsTemplate;

import common.SimpleMessage;

public class MessageProducerRunner implements Runnable {

	private static Logger log = Logger.getLogger(MessageProducerRunner.class);
	private static int nextId = 1;

	private int id;
	private boolean stop = false;
	private int nextMessage = 1;

	private JmsTemplate jmsTemplate;

	public MessageProducerRunner() {
		this.id = nextId++;
	}

	public MessageProducerRunner(JmsTemplate jmsTemplate) {
		this.id = nextId++;
		setJmsTemplate(jmsTemplate);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		log.info("Starting: " + id);
		for (int i = 0; i < 10; i++) {
			 try {
				 Thread.sleep(100);
			 } catch (InterruptedException e) {}

			if (stop) {
				break;
			}

			SimpleMessage msg = new SimpleMessage("Runner #" + getId()
					+ " - message #" + nextMessage++);
			jmsTemplate.convertAndSend(msg);
			log.trace("Sending: " + msg.getText());
		}
		log.info("Stoping: " + id);
	}

	public void stop() {
		synchronized (this) {
			this.stop = true;
		}
		this.notify();
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getNextMessage() {
		return nextMessage;
	}

	public void setNextMessage(int nextMessage) {
		this.nextMessage = nextMessage;
	}

	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

}
